package com.batchOperation.Template.serviceImpl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.batchOperation.businessfield.EntityFieldService;
import com.batchOperation.businessfield.model.BusinessEntityField;
import com.batchOperation.Template.TemplateService;
import com.batchOperation.Template.model.BatchOperationTemplate;
import com.batchOperation.Template.model.BatchOperationTemplateContent;
import com.batchOperation.excel.model.Employee;
import com.batchOperation.excel.model.SchoolInfo;
import com.batchOperation.excel.support.ExcelConstant;
import com.batchOperation.excel.support.MappingHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @Package: com.geeksss.excel.Template
 * @ClassName: TemplateService
 * @Author: wulongkai
 * @CreateTime: 2024/7/18 17:06
 * @Description:
 */
@Service
public class TemplateServiceImpl implements TemplateService {

    @Autowired
    private EntityFieldService entityFieldService;

    private static Map<Long, BatchOperationTemplate> db = new ConcurrentHashMap<>();

    static {
        BatchOperationTemplate batchOperationTemplate = new BatchOperationTemplate();
        batchOperationTemplate.setTemplateId(1024L);
        batchOperationTemplate.setTemplateName("测试名称");
        batchOperationTemplate.setContents(new ArrayList<>());

        List<BatchOperationTemplateContent> contents = batchOperationTemplate.getContents();
        for (Field declaredField : SchoolInfo.class.getDeclaredFields()) {
            if (declaredField.getName().equals("userRank"))
                continue;
            BatchOperationTemplateContent content = new BatchOperationTemplateContent();
            content.setEntity(SchoolInfo.class.getSimpleName());
            content.setFieldId(declaredField.getName());
            contents.add(content);
        }
        for (Field declaredField : Employee.class.getDeclaredFields()) {
            if (declaredField.getName().equals("userRank"))
                continue;
            BatchOperationTemplateContent content = new BatchOperationTemplateContent();
            content.setEntity(Employee.class.getSimpleName());
            content.setFieldId(declaredField.getName());
            contents.add(content);
        }

        batchOperationTemplate.setEntityList(new ArrayList<>());
        batchOperationTemplate.getEntityList().add(Employee.class.getSimpleName());
        batchOperationTemplate.getEntityList().add(SchoolInfo.class.getSimpleName());

        db.put(batchOperationTemplate.getTemplateId(), batchOperationTemplate);
    }

    public BatchOperationTemplate getTemplateInfo(Long templateId) {
        return db.get(templateId);
    }

    public Map<String, List<BusinessEntityField>> getBatchOperationTemplateList(String mainObj) {
        Map<String, List<BusinessEntityField>> entity2Fields = new HashMap<>();
        if (mainObj.equals("Employee")) {
            List<String> entityList = Arrays.asList("Employee", "schoolInfo");
            for (String entity : entityList) {
                List<BusinessEntityField> businessEntityField = entityFieldService.getBusinessEntityField(entity);
                entity2Fields.put(entity, businessEntityField);
            }
        }
        return entity2Fields;
    }

    public void createOrModifyTemplate(BatchOperationTemplate batchOperationTemplate) {
        // 先只处理新增
        List<BatchOperationTemplateContent> contents = batchOperationTemplate.getContents();
        Map<String, List<BatchOperationTemplateContent>> entityAndEntityName2Content = contents.stream()
                .collect(Collectors.groupingBy(
                        BatchOperationTemplateContent::getEntity,
                        Collectors.toList()
                ));
        // 创建自定义比较器，基于 entityList
        Comparator<String> comparator = Comparator.comparingInt(batchOperationTemplate.getEntityList()::indexOf);
        TreeMap<String, List<BatchOperationTemplateContent>> sortedMap = new TreeMap<>(comparator);
        sortedMap.putAll(entityAndEntityName2Content);

        // 生成 excel
        String fileName = ExcelConstant.path + "template-" + batchOperationTemplate.getTemplateName() + System.currentTimeMillis() + ".xlsx";
        try (ExcelWriter excelWriter = EasyExcel.write(fileName).build()) {
            int sheetNo = 0;
            for (Map.Entry<String, List<BatchOperationTemplateContent>> entry : sortedMap.entrySet()) {
                String entity = entry.getKey();
                List<String> includeColumnFieldNames = entry.getValue().stream().map(BatchOperationTemplateContent::getFieldId).collect(Collectors.toList());
                WriteSheet sheet = EasyExcel.writerSheet(sheetNo++, MappingHandler.entity2SheetName.get(entity))
                        .head(MappingHandler.entity2Class.get(entity))
                        .includeColumnFieldNames(includeColumnFieldNames)
                        .build();
                excelWriter.write(Collections.EMPTY_LIST, sheet);
            }
        }

        db.put(batchOperationTemplate.getTemplateId(), batchOperationTemplate);
    }
}
